package com.atguigu.controller;

import com.atguigu.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/consumer")
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("/{id}")
    public User findById(@PathVariable("id") Integer id){
        List<ServiceInstance> instances = discoveryClient.getInstances("user-provider");
        ServiceInstance serviceInstance = instances.get(0);
        //String url = "http://localhost:18081/user/find/"+id;
        String url = "http://"+serviceInstance.getHost()+":" +
                +serviceInstance.getPort()+"/"+"user/find/"+id;
        return restTemplate.getForObject(url, User.class);
    }
}
